package com.bitcointoolkit.web.controller;

import com.alibaba.fastjson.JSON;
import com.bitcointoolkit.web.service.tx.DecodedTx;
import com.bitcointoolkit.web.service.tx.TxService;
import com.bitcointoolkit.web.support.ErrorEnum;
import com.bitcointoolkit.web.support.ErrorResult;
import com.bitcointoolkit.web.support.Result;
import com.bitcointoolkit.web.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 */
@Controller
@RequestMapping("/tx")
@Slf4j
public class TxController extends BaseController {

    @Autowired
    TxService txService;

    /**
     * @param model
     * @param rawhex
     * @return
     */
    @RequestMapping({"/decodetx"})
    @ResponseBody
    public String decodeTx(Model model, @RequestParam(value = "rawhex") String rawhex) {
        if (rawhex.length() == 0) {
            return new ErrorResult(ErrorEnum.ARGUMENT_INVALID).toString();
        }

        Result<DecodedTx> result = txService.decodeRawTx(rawhex);
        if (result.isSuccess()) {
            return JSON.toJSONString(result.getData());
        } else {
            return new ErrorResult(ErrorEnum.QUERY_FAILED).toString();
        }
    }

    @RequestMapping(value = "/test", method={RequestMethod.GET, RequestMethod.POST})
    public void decodeTx(@RequestParam(required = false) Date date,
                           HttpServletRequest request, HttpServletResponse response) {
        Date startTime,endTime;
        if (date == null) {
            Date targetDay = DateUtil.anyDay(new Date(),-1);
            String targetDayStr = DateUtil.format(targetDay,"yyyy-MM-dd");
            startTime = DateUtil.parseDate2(targetDayStr);
            endTime = DateUtil.afterDay(startTime, 1);
        } else {
            startTime = date;
            endTime = DateUtil.afterDay(startTime, 1);
        }
        log.info("execute statistic. input date: {}, startTime: {}, endTime: {}", date,
                DateUtil.format(startTime ,DateUtil.SHOW_DATETIME_FORMAT),
                DateUtil.format(endTime ,DateUtil.SHOW_DATETIME_FORMAT));

        response.setStatus(HttpServletResponse.SC_OK);
    }

}
